package emqx

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"log/slog"
	"statsphere/internal/bytesconv"
	"statsphere/pkg/gwprop"
	"statsphere/pkg/uuid"
	"time"
)

var (
	mqClient     mqtt.Client
	topicCollect string
)

func Setup() {
	slog.Warn("emqx_go_file_init")

	clientID := uuid.NewString()

	emqxIp := gwprop.GetProp().EMQIP
	if len(gwprop.GetProp().GWEMQDOMAIN) > 0 {
		emqxIp = gwprop.GetProp().GWEMQDOMAIN
	}
	server := fmt.Sprintf("tcp://%s:%s", emqxIp, gwprop.GetProp().EMQPORT)
	slog.Warn("emqx_config", "emq_server", server, "client_id", clientID)

	opt := mqtt.NewClientOptions().
		AddBroker(server).
		SetUsername(gwprop.GetProp().EMQUSER).
		SetPassword(gwprop.GetProp().EMQPWD).
		SetClientID(clientID).
		SetAutoReconnect(true).
		SetConnectTimeout(5 * time.Second).
		SetWriteTimeout(15 * time.Second).
		SetConnectionLostHandler(defaultConnectionLostHandler).
		SetReconnectingHandler(defaultReconnectHandler)
	mqClient = mqtt.NewClient(opt)

	token := mqClient.Connect()
	token.Wait()
	if token.Error() != nil {
		slog.Error("emqx_conn_err", "error", token.Error())
	}
	token = nil
	slog.Info("emqx_连接完成")
	// com/2000000007/1567325117245472774/
	// topicCollect = fmt.Sprintf("com/%s/%s/collect/0", m.EPID, m.GWID)
	topicCollect = "com/gateway/collect/log/topic"
}

func PushMqttData(data []byte) {
	var token mqtt.Token
	if !mqClient.IsConnected() {
		token = mqClient.Connect()
		token.Wait()
	}
	token = mqClient.Publish(topicCollect, 1, false, data)
	token.Wait()
	// 发送失败, 塞进队列
	tokenError := token.Error()
	if tokenError != nil {
		// SaveMq(data)
	} else {
		slog.Info("emq_success_data" + bytesconv.BytesToString(data))
	}
	tokenError = nil
	data = nil
}

//func SaveMq(msg []byte) {
//	jsonError <- msg
//}

func defaultConnectionLostHandler(client mqtt.Client, reason error) {
	slog.Error("emqx_conn_lost:" + reason.Error())
}

func defaultReconnectHandler(client mqtt.Client, opt *mqtt.ClientOptions) {
	slog.Warn("emqx_conn_reconnect")
}
